package ru.samgtu.wst.parser;

import ru.samgtu.wst.model.HttpUrl;
import ru.samgtu.wst.model.Message;
import ru.samgtu.wst.util.MRUCache;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Logger;

public class Parser {

	private static List _parsers = new ArrayList();
	private static Logger _logger = Logger
			.getLogger("ru.samgtu.wst.parser.Parser");

	// we cache the 8 most recent messages and their parsed versions
	private static MRUCache _cache = new MRUCache(8);

	static {
		_parsers.add(new HTMLParser());
	}

	/** Creates a new instance of Parser */
	private Parser() {
	}

	/**
	 * returns a parsed representation of the message, requesting the parsers to
	 * resolve any links relative to the url provided
	 */
	public static Object parse(HttpUrl url, Message message) {
		if (_cache.containsKey(message)) {
			return _cache.get(message);
		}
		Iterator it = _parsers.iterator();
		Object parsed = null;
		ContentParser parser;
		while (it.hasNext()) {
			parser = (ContentParser) it.next();
			parsed = parser.parseMessage(url, message);
			if (parsed != null) {
				break;
			}
		}
		_cache.put(message, parsed);
		return parsed;
	}

}
